using System;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Admin3000.Backend.Api.Utils;
using Admin3000.Backend.Api.Entity;
using Admin3000.Backend.Api.ParamModel;
using Admin3000.Backend.Api.Repository;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Authorization;

namespace Admin3000.Backend.Controllers
{
    [Authorize]
    [ApiController]
    [Route("[controller]")]
    public class UsersController : ControllerBase
    {
        private IRepository<Users> _usersRespository;
        private TokenParameter _tokenParameter;
        private readonly IConfiguration _configuration;

        public UsersController(IConfiguration configuration, IRepository<Users> usersRespository)
        {
            _configuration = configuration;
            _usersRespository = usersRespository;
            _tokenParameter = _configuration.GetSection("TokenParameter").Get<TokenParameter>();
        }

        [HttpGet]
        public dynamic Get([FromQuery] QueryWithPager query)
        {//get请求默认从uri从获取参数，所以此处应该加上FromQuery的特性才能正确获得参数
            var pageIndex = query.Pager.PageIndex;
            var pageSize = query.Pager.PageSize;
            var keyword = string.IsNullOrEmpty(query.Keyword) ? "" : query.Keyword.Trim();

            // 获得所有满足条件的记录
            var users = _usersRespository.Table.Where(x => x.IsDeleted == false);

            // 如果存在关键字，则对用户名进行查询，此处只是一个演示，可以根据实际情况对昵称、角色名等进行模糊查询
            if (!string.IsNullOrEmpty(keyword))
            {
                users = users.Where(x => x.Username.Contains(keyword));
            }

            // 对获得的记录分页
            var u = users.OrderByDescending(x => x.Id).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();

            // 返回的数据里，带有数据和分页信息
            var res = new
            {
                Code = 1000,
                Data = new { Data = u, Pager = new { pageIndex, pageSize, rowsTotal = users.Count() } },
                Msg = "获取用户列表成功^_^"
            };
            return res;
        }

        [HttpGet("{id}")]
        public dynamic Get(int id)
        {
            var user = _usersRespository.GetById(id);

            if (user == null)
            {
                return new
                {
                    Code = 1000,
                    Data = "",
                    Msg = "指定用户不存在"
                };

            }
            return new
            {
                Code = 1000,
                Data = user,
                Msg = "获取用户列表成功^_^"
            };

        }

        [HttpPost]
        public string Post(NewUser model)
        {
            var username = model.Username.Trim();
            var nickname=model.Nickname.Trim();
            var avatarId=model.AvatarId;
            var password = model.Password.Trim();
            var remarks = model.Remarks.Trim();

            if (string.IsNullOrEmpty(username))
            {
                var tmp = new
                {
                    Code = 1004,
                    Data = "",
                    Msg = "用户名不能为空，请确认后重试"
                };
                return JsonHelper.Serialize(tmp);
            }

            var user = new Users
            {
                Username = username,
                Password = "113",
                Nickname=nickname,
                AvatarId=avatarId,
                Remarks = remarks
            };

            _usersRespository.Insert(user);

            var res = new
            {
                Code = 1000,
                Data = user,
                Msg = "创建用户成功"
            };
            return JsonHelper.Serialize(res);
        }

        [HttpPut("{id}")]
        public dynamic Put(int id, NewUser model)
        {
            var user = _usersRespository.GetById(id);

            if (user != null)
            {
                user.Username = model.Username;
                // user.Password = model.Password;
                user.Nickname=model.Nickname;
                user.AvatarId=model.AvatarId;
                user.Remarks = model.Remarks;
                user.UpdatedTime = DateTime.Now;
                _usersRespository.Update(user);
                return JsonHelper.Serialize(new
                {
                    Code = 1000,
                    Data = user,
                    Msg = string.Format("你修改的用户的id为：{0}，已经修改成功，请注意查收", id)
                });
            }
            else
            {
                return JsonHelper.Serialize(new
                {
                    Code = 104,
                    Data = "",
                    Msg = "指定Id的用户不存在，请确认后重试"
                });
            }
        }

        [HttpDelete("{id}")]
        public dynamic Delete(int id)
        {
            var user = _usersRespository.GetById(id);
            if (user != null)
            {
                if (user.IsDeleted)
                {
                    return new
                    {
                        Code = 104,
                        Msg = string.Format("该用户已经删除！", id)
                    };
                }
                user.IsDeleted = true;
                user.UpdatedTime = DateTime.Now;
                _usersRespository.Update(user);
                return new
                {
                    Code = 1000,
                    Msg = string.Format("删除指定id为{0}的用户成功", id)
                };
            }
            else
            {
                return new
                {
                    Code = 104,
                    Data = "",
                    Msg = "指定Id的用户不存在，请确认后重试"
                };
            }

        }

        [AllowAnonymous]
        [HttpPost, Route("token")]
        public dynamic GetToken(NewUser model)
        {
            var username = model.Username.Trim();
            var password = model.Password.Trim();

            var user = _usersRespository.Table.Where(x => x.Username == username && x.Password == password).FirstOrDefault();

            if (user == null)
            {
                return new
                {
                    Code = 1001,
                    Data = user,
                    Msg = "用户名或密码不正确，请核对后重试"
                };
            }

            var token = TokenHelper.GenerateToken(_tokenParameter, user.Username);
            var refreshToken = "112358";

            var res = new
            {
                Code = 1000,
                Data = new { Token = token, RefreshToken = refreshToken },
                Msg = "用户登录成功，获取token成功"
            };
            return res;
        }

        [AllowAnonymous]
        [HttpPost, Route("refreshToken")]
        public dynamic RefreshToken(RefreshTokenParam model)
        {
           var username = TokenHelper.ValidateToken(_tokenParameter, model);

            if (string.IsNullOrEmpty(username))
            {
                return new { Code = 1002, Data = "", Msg = "token验证失败" };
            }

            var token = TokenHelper.GenerateToken(_tokenParameter, username);
            var refreshToken = "112358";

            return new
            {
                Code = 1000,
                Data = new { Token = token, refreshToken = refreshToken },
                Msg = "刷新token成功^_^"
            };
        }
    }
}
